<template>
  <j-modal
    :title="title"
    :width="600"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
    :draggable="true"  
  >
    <a-card :bordered="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <!-- <a-form-item
          label="已选择的报告"
          :labelCol="{ lg: { span: 4 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 20 }, sm: { span: 17 } }"
        >
          <a-tag color="blue">{{ selectionRow.reportName }}</a-tag>
        </a-form-item> -->

        <a-form-model-item
          label="计算日期"
          :labelCol="{ lg: { span: 7 }, sm: { span: 7 } }"
          :wrapperCol="{ lg: { span: 17 }, sm: { span: 17 } }"
          prop="calcDate"
        >
          <a-date-picker v-model="model.calcDate"></a-date-picker>
           <a-checkbox v-model="model.rebuild" style="margin-left:10px;">
                  重新生成
            </a-checkbox>
        </a-form-model-item>  
      </a-form-model>
    </a-card>
    <j-modal
      :width="1000"
      :maskClosable="false"
      switchFullscreen
      :fullscreen="true"
      :visible="resultVisible"
      :title="selectionRow.reportName"
      @cancel="handleResultCancel"
    >
      <template>
        <a-form layout="inline">
          <a-row style="margin-bottom: 12px">
            <a-col :md="6" :xs="24">
              <a-form-item
                label="报告名称："
                :labelCol="{ md: 4, xs: 24 }"
                :wrapperCol="{ md: 18, xs: 24 }"
                style="width: 100%"
              >
                {{ selectionRow.reportName }}
              </a-form-item>
            </a-col>
            <a-col :md="6" :xs="24">
              <a-form-item
                label="计算日期："
                :labelCol="{ md: 4, xs: 24 }"
                :wrapperCol="{ md: 18, xs: 24 }"
                style="width: 100%"
              >
                {{ selectDate }}
              </a-form-item>
            </a-col>
            <a-col :md="4" :xs="24">
              <!-- <a-button type="primary" icon="download" @click="handleExportXls()" :loading="loading">导出</a-button> -->
                <a-button   :ghost="true" type="primary" icon="download" size="small" @click="downloadFile()">
            下载
          </a-button>
            </a-col>
          </a-row>
        </a-form> 
        <a-table
          ref="table"
          size="middle"
          
          bordered
          :columns="columns"
          :dataSource="tbList"
          :pagination="false"
          class="j-table-force-nowrap"
        >
        </a-table>
      </template>
      <template slot="footer">
        <a-button @click="buildReportResultCancel">关闭</a-button>
      </template>
    </j-modal>
  </j-modal>
</template> 

<script>
import moment from 'moment'
import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
export default {
  name: 'runModal',
  components: {},
  data() {
    return {
      title: '生成报告',
      width: 900,
      visible: false,
      selectionRow: {},
      model: {
        reportId: '',
        calcDate: '', //计算时间
        rebuild: false,
      },
      selectDate: '', // =计算时间 格式 （yyyy-MM-dd）
      validatorRules: {
        calcDate: [{ required: true, message: '请选择计算时间!' }],
      },
      resultVisible: false,
      tbList: [], //
      confirmLoading: false,
      loading: false,
      columns: [],
      url: {
        exportXlsUrl: '/userReports/userReports/exportXls2',
        queryById: '/userReports/userReports/queryById',
      },
    }
  },
  methods: {
    show(selectionRow) {
      this.selectionRow = selectionRow
      this.title = '生成报告 - 【 ' + this.selectionRow.reportName + ' 】 '
      this.model = Object.assign(
        {},
        {
          reportId: selectionRow.id,
          calcDate: moment(new Date()).format('YYYY-MM-DD'), //计算时间
          rebuild: false,
        }
      )
      this.visible = true
      this.confirmLoading = false
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      var that = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          var param = Object.assign({}, that.model)
          param.calcDate = moment(that.model.calcDate).format('YYYY-MM-DD')
          that.selectDate = param.calcDate
          postAction('/userReports/userReports/buildReport', param).then((res) => {
            this.confirmLoading = false
            if (res.success) {
              that.resultVisible = true
              var data = res.result
              var fileNames = data.userReportsFieldList;//列名用 自定义列 （序号排序）
              var existData = data.existData;//是否存在数据
              that.columns = [
                {
                  title: '槽号',
                  align: 'center',
                  dataIndex:existData?'slot':'slotNo'
                },
              ] 
              that.tbList = []
              for (let i = 0; i < fileNames.length; i++) {
                const element = fileNames[i];
                  that.columns.push({
                  title: element.fieldName,
                  dataIndex:existData? element.tableColumn : element.fieldName, 
                  align: 'center',
                })
              } 
              console.log('that.columns:',JSON.stringify(that.columns));
              if(existData){ //存在数据
                that.tbList = data.result
                return
              } 
              // for (const key in data) {
              //   that.columns.push({
              //     title: key,
              //     dataIndex: key, 
              //     align: 'center',
              //   })
              // }

              for (const key in data[that.columns[1].title]) {
                var obj = { slotNo: key }
                for (let i = 1; i < that.columns.length; i++) {
                  const element = that.columns[i]
                  obj[element.dataIndex] = ''
                }
                that.tbList.push(obj)
              }

              for (let i = 0; i < that.tbList.length; i++) {
                const row = that.tbList[i]
                for (const key in row) {
                  if (key != 'slotNo') {
                    row[key] = data[key][row['slotNo']]
                  }
                }
              }
            } else {
              that.$message.error(res.message)
            }
          })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handleResultCancel(){
      this.resultVisible = false;
    },
    buildReportResultCancel() {
      this.resultVisible = false
      this.tbList = []
    },
    downloadFile() {
      var that =this;
      getAction(that.url.queryById,{id:this.model.reportId}).then((res)=>{
          if(res.success){
              var text = res.result.url;
              if (!text) {
                that.$message.warning('未知的文件')
                return
              }
              if (text.indexOf(',') > 0) {
                text = text.substring(0, text.indexOf(','))
              }
              let url = window._CONFIG['domianURL'] + '/sys/common/download/' + text
              window.open(url)
          }else{
            that.$message.warning(res.message);
          }
        }); 
    }, 
    handleExportXls(fileName) {
      var that = this
      var fileName = that.selectionRow.reportName
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      var param = Object.assign({}, that.model)
      param.calcDate = moment(that.model.calcDate).format('YYYY-MM-DD')
      that.loading = true
      // console.log("导出参数",param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        that.loading = false
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>

<style scoped>
</style>